//+------------------------------------------------------------------+
//|                                                         6666.mq5 |
//|                                  Copyright 2025, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

// 输入参数
input ulong      InpMagicNumber = 123456;     // EA魔术编号
input string     InpNoTradeTimeStart = "19:30"; // 不交易时间段开始(服务器时间)
input string     InpNoTradeTimeEnd = "23:30";   // 不交易时间段结束(服务器时间)



input double     InpThreshold1 = 0.16;          // 第一层止盈手数阈值
input double     InpThreshold2 = 8.32;          // 第二层止盈手数阈值
input double     InpThreshold3 = 10.0;          // 第三层止盈手数阈值
input double     InpThreshold4 = 20.0;          // 第四层止盈手数阈值

// 第一层止盈参数
input int        InpProfitMode = 1;           // 第一层盈利模式(0=乘数,1=固定)
input double     InpProfitMultiplier = 1.0;   // 第一层乘数/固定金额

// 第二层止盈参数
input int        InpProfitMode1 = 1;          // 第二层盈利模式(0=乘数,1=固定)
input double     InpProfitMultiplier1 = 2.0;  // 第二层乘数/固定金额

// 第三层止盈参数
input int        InpProfitMode2 = 1;          // 第三层盈利模式(0=乘数,1=固定)
input double     InpProfitMultiplier2 = 3.0;  // 第三层乘数/固定金额

// 第四层止盈参数
input int        InpProfitMode3 = 1;          // 第四层盈利模式(0=乘数,1=固定)
input double     InpProfitMultiplier3 = 4.0;  // 第四层乘数/固定金额

// 第五层止盈参数
input int        InpProfitMode4 = 1;          // 第五层盈利模式(0=乘数,1=固定)
input double     InpProfitMultiplier4 = 5.0;  // 第五层乘数/固定金额

input int        InpMAPeriod1 = 5;            // 均线1周期
input int        InpMAPeriod2 = 10;           // 均线2周期
input int        InpMAPeriod3 = 15;           // 均线3周期
input int        InpMAPeriod4 = 20;           // 均线4周期
input int        InpMAPeriod5 = 25;           // 均线5周期
input int        InpMAPeriod6 = 30;           // 均线6周期
input ENUM_APPLIED_PRICE InpMAAppliedPrice = PRICE_CLOSE; // 均线应用价格
input ENUM_MA_METHOD InpMAMethod = MODE_SMA;  // 均线计算方法

// 全局变量
int maHandles[6];        // 均线指标句柄数组
double maValues[6];      // 均线值数组
datetime lastBarTime = 0;// 最后处理的K线时间
bool filterEnabled = false; // 持仓过滤开关状态
long chartID = 0;       // 图表ID
int buttonId = 1;       // 按钮ID

//+------------------------------------------------------------------+
//| 获取周期名称函数                                                 |
//+------------------------------------------------------------------+
string GetPeriodName()
{
   switch(_Period)
   {
      case PERIOD_M1:  return "M1";
      case PERIOD_M2:  return "M2";
      case PERIOD_M3:  return "M3";
      case PERIOD_M4:  return "M4";
      case PERIOD_M5:  return "M5";
      case PERIOD_M6:  return "M6";
      case PERIOD_M10: return "M10";
      case PERIOD_M12: return "M12";
      case PERIOD_M15: return "M15";
      case PERIOD_M20: return "M20";
      case PERIOD_M30: return "M30";
      case PERIOD_H1:  return "H1";
      case PERIOD_H2:  return "H2";
      case PERIOD_H3:  return "H3";
      case PERIOD_H4:  return "H4";
      case PERIOD_H6:  return "H6";
      case PERIOD_H8:  return "H8";
      case PERIOD_H12: return "H12";
      case PERIOD_D1:  return "D1";
      case PERIOD_W1:  return "W1";
      case PERIOD_MN1: return "MN1";
      default:         return "Unknown";
   }
}

//+------------------------------------------------------------------+
//| 平掉所有当前品种的持仓                                           |
//+------------------------------------------------------------------+
void CloseAllPositions()
{
   // 遍历所有持仓
   int total = PositionsTotal();
   for(int i = total-1; i >= 0; i--) // 从后往前遍历，因为平仓会改变持仓顺序
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket > 0 && PositionGetString(POSITION_SYMBOL) == _Symbol)
      {
         // 获取持仓信息
         double volume = PositionGetDouble(POSITION_VOLUME);
         ENUM_POSITION_TYPE type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
         
         // 创建平仓请求
         MqlTradeRequest request;
         ZeroMemory(request);
         request.action = TRADE_ACTION_DEAL;
         request.position = ticket;
         request.symbol = _Symbol;
         request.volume = volume;
         request.deviation = 5;
         request.magic = InpMagicNumber;
         
         // 设置平仓方向
         if(type == POSITION_TYPE_BUY)
            request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         else
            request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            
         request.type = (type == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
         
         // 发送平仓请求
         MqlTradeResult result;
         ZeroMemory(result);
         if(OrderSend(request, result))
         {
            Print("成功平仓 #", ticket, " 手数: ", volume, " 类型: ", EnumToString(type));
         }
         else
         {
            Print("平仓失败 #", ticket, " 错误: ", GetLastError());
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // 打印当前品种、周期和魔术编号
   Print("EA初始化 - 魔术编号: ", InpMagicNumber);
   Print("当前交易品种: ", _Symbol, " | 当前周期: ", GetPeriodName());
   Print("均线参数: ", InpMAPeriod1, ", ", InpMAPeriod2, ", ", InpMAPeriod3, ", ",
         InpMAPeriod4, ", ", InpMAPeriod5, ", ", InpMAPeriod6);
   Print("盈利乘数: ", InpProfitMultiplier);
   Print("不交易时间段: ", InpNoTradeTimeStart, " 至 ", InpNoTradeTimeEnd);
   return(INIT_SUCCEEDED);
}



//+------------------------------------------------------------------+
//| 检查当前持仓情况并打印信息                                       |
//+------------------------------------------------------------------+
void CheckCurrentPositions()
{
   double totalVolume = 0.0;
   double totalProfit = 0.0;
   double aim = 0.0;
   int positionsCount = 0;
   
   // 直接遍历所有持仓
   int total = PositionsTotal();
   for(int i = 0; i < total; i++)
   {
      if(PositionGetSymbol(i) == _Symbol)
      {
         totalVolume += PositionGetDouble(POSITION_VOLUME);
         totalProfit += PositionGetDouble(POSITION_PROFIT);
         positionsCount++;
      }
   }
   
   if(positionsCount > 0)
   {
      Print("当前持仓 - 总手数: ", totalVolume, ", 总盈利: ", totalProfit, " ", AccountInfoString(ACCOUNT_CURRENCY), 
            ", 持仓数量: ", positionsCount);
   }
   else
   {
      Print("当前没有持仓");
      return; // 没有持仓直接返回
   }

   // 根据持仓量选择止盈层级
   int currentProfitMode;
   double currentMultiplier;
   string levelDesc;
   
   if(totalVolume <= InpThreshold1)
   {
      currentProfitMode = InpProfitMode;
      currentMultiplier = InpProfitMultiplier;
      levelDesc = "第一层级";
   }
   else if(totalVolume > InpThreshold1 && totalVolume <= InpThreshold2)
   {
      currentProfitMode = InpProfitMode1;
      currentMultiplier = InpProfitMultiplier1;
      levelDesc = "第二层级";
   }
   else if(totalVolume > InpThreshold2 && totalVolume <= InpThreshold3)
   {
      currentProfitMode = InpProfitMode2;
      currentMultiplier = InpProfitMultiplier2;
      levelDesc = "第三层级";
   }
   else if(totalVolume > InpThreshold3 && totalVolume <= InpThreshold4)
   {
      currentProfitMode = InpProfitMode3;
      currentMultiplier = InpProfitMultiplier3;
      levelDesc = "第四层级";
   }
   else
   {
      currentProfitMode = InpProfitMode4;
      currentMultiplier = InpProfitMultiplier4;
      levelDesc = "第五层级";
   }

   // 根据盈利模式计算目标
   switch(currentProfitMode)
   {
      case 0: // 乘数模式
         aim = totalVolume * 100 * currentMultiplier;
         Print(levelDesc, " 目标盈利（乘数模式）: ", aim, " (手数×100×", currentMultiplier, ")");
         break;
         
      case 1: // 固定金额模式
         aim = currentMultiplier;
         Print(levelDesc, " 目标盈利（固定金额模式）: ", aim, " (固定", currentMultiplier, " ", AccountInfoString(ACCOUNT_CURRENCY), ")");
         break;
         
      default:
         Print("错误: 未知的盈利模式 ", currentProfitMode);
         return;
   }

   // 比较总盈利和目标
   if(totalProfit > aim)
   {
      Print("达到平仓条件(盈利 ", totalProfit, " > 目标 ", aim, ")，开始平掉所有持仓...");
      CloseAllPositions();
   }
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{

   // 检查当前持仓情况
   CheckCurrentPositions();
   
}
